import {Component, Input, OnInit} from '@angular/core';
import {WmsPurchaseOrderSelf, WmsPurchaseOrderSelfCondition} from '../../wms-purchase-order-self.type';
import {ActivatedRoute, Router} from '@angular/router';
import {Services} from '../../../../../frame/module/services';
import {ErrRes} from '../../../../../frame/global/err-res';
import {isNullOrUndefined} from 'util';
import {UrlRou} from '../../../../../frame';
import {ModifyWmsPurchaseOrderSelfComponent} from '../modify-wms-purchase-order-self.component';
import {Zero3Alert} from '../../../../../frame/global/zero3-alert/zero3-alert.component';
import {Zero3Enum} from '../../../../../frame/enum/zero3-enum';
import * as fa from '@fortawesome/free-solid-svg-icons';
import {HttpRequestClient} from '../../../../../frame/http-request-client/http-request-client';
import {WmsWarehouseManageCondition} from '../../../wms-warehouse-manage/wms-warehouse-manage.type';

@Component({
    selector: 'app-main-modify-wms-purchase-order-self',
    templateUrl: './main-modify-wms-purchase-order-self.component.html',
    styleUrls: ['./main-modify-wms-purchase-order-self.component.css']
})
export class MainModifyWmsPurchaseOrderSelfComponent implements OnInit {

    errRes = new ErrRes();

    domain = new WmsPurchaseOrderSelf();
    // 仓库类型
    hoseTypes = [];
    // 表单数据
    formData = {
        orderId: '',
        wmsHoseId: null, // 仓库ID
        remark: '', // 备注
    };
    // 表格数据
    tableData = {
        title: [],
        data: []
    };

    utils = {
        checkTablesData: item => {
            if (!item || item <= 0) {
                return false;
            }
            return true;
        }
    };
    extend = {
        domain: {
            default: () => {
                this.domain.serAudit = Zero3Enum.AUDIT_FLAG_WAIT_SUBMIT;
                this.domain.serUsing = Zero3Enum.ENABLE;
                this.extend.domain.serAudit.nickname = Zero3Enum.AUDIT_FLAG.get(this.domain.serAudit);
            },
            serAudit: {
                nickname: ''
            },
            file: {
                oss: Services.aliOSS.simple(),
                change: (event) => {
                    console.log(event.target.value); // file name
                    this.extend.domain.file.oss.uploadFile((response, status, headers) => {
                        if (status === 200) {
                            this.extend.domain.file.oss.fileUrl = JSON.parse(response).detail.fileUrl;
                            this.domain.serFileUrl = this.extend.domain.file.oss.fileUrl;
                        } else {
                            this.extend.domain.file.oss.fileUrl = '';
                            this.domain.serFileUrl = this.extend.domain.file.oss.fileUrl;
                            Zero3Alert.req('fail');
                        }
                    });
                }
            },
            serInputGroupData: {
                icon: fa.faCalendar,
                nickname: '日期',
                value: () => {
                    return this.domain.serInputGroupData;
                },
                focus: (event) => {
                    this.domain.serInputGroupData = event.target.value.toString();
                },
                blur: (event) => {
                }
            },
        },
    };

    func = {
        save: {
            req: (event) => {
                Services.wmsPurchaseOrderSelf.save(this.domain, this.func.save.callback).subscribe();
            },
            callback: {
                success: (result) => {
                    HttpRequestClient.router.navigate([UrlRou.wmsPurchaseOrderSelf.list]);
                },
                error: (result) => {
                    this.errRes.error = result.error;
                    this.errRes.statusText = result.statusText;
                }
            }
        },
        loadHouses: () => {
            Services.wmsWarehouseManage
                .list(new WmsWarehouseManageCondition(), {page: 0, size: 1000, orders: 'createTime-desc,serNum-asc'})
                .subscribe(houses => {
                    this.hoseTypes = [];
                    houses.page.content.forEach(gooBaseGoodsSpecification => {
                        this.hoseTypes.push(
                            {id: gooBaseGoodsSpecification.uuid, name: gooBaseGoodsSpecification.serName}
                        );
                    });
                });
        },
        loadDomain: (uuid: string) => {
            const condition: WmsPurchaseOrderSelfCondition = new WmsPurchaseOrderSelfCondition();
            condition.uuid = uuid;
            Services.wmsPurchaseOrderSelf.info(condition).subscribe(item => {
                console.log(item);
                this.tableData.data = item.domain.wmsPurchaseOrderLines;
                this.formData.wmsHoseId = item.domain.wmsHorseUUID;
                this.formData.remark = item.domain.serMemo;
                this.formData.orderId = item.domain.uuid;

            });
        }
    };


    constructor(public addWmsPurchaseOrderSelf: ModifyWmsPurchaseOrderSelfComponent, public router: Router, private route: ActivatedRoute) {
        this.addWmsPurchaseOrderSelf.main = this;
    }

    ngOnInit() {
        this.extend.domain.default();
        this.func.loadHouses();
        const uuid = this.route.snapshot.paramMap.get('uuid');
        this.func.loadDomain(uuid);
    }


    // 添加商品
    addGoods(item) {
        this.tableData.data.push(item);
    }

    // 生成采购单
    doSaveOrder(operateType) {
        console.log(this.tableData.data);
        if (this.tableData.data.length <= 0) {
            return Zero3Alert.req('请选择商品');
        }
        if (!this.formData.wmsHoseId) {
            return Zero3Alert.req('请选择仓库！');
        }
        const utils = this.utils;
        const checkFlag = this.tableData.data.every(item => {
            if (!utils.checkTablesData(item.goodsNum) ||
                !utils.checkTablesData(item.singlePrice) ||
                !utils.checkTablesData(item.totalPrice)) {
                return false;
            }
            return true;
        });
        console.log(checkFlag);
        if (!checkFlag) {
            return Zero3Alert.req('商品参数错误！');
        }
        const params = this.buildOrderData(this.tableData.data, this.formData, operateType);
        console.log(params);

        Services.wmsPurchaseOrderSelf.update(params, {
            success: data => {
                Zero3Alert.req('修改成功！');
            }, error: data => {
                Zero3Alert.req('修改失败！');
            }
        }).subscribe(() => {
            this.router.navigate([UrlRou.wmsPurchaseOrderSelf.list]);
        });

    }

    // 构建服务器数据格式
    buildOrderData(tables, formData, operateType) {
        return {
            uuid: formData.orderId,
            wmsHorseId: formData.wmsHoseId,
            remark: formData.remark,
            operateType: operateType,
            formLines: tables
        };
    }

    goList() {
        this.router.navigate([UrlRou.wmsPurchaseOrderSelf.list]);
    }
}
